#!/bin/bash

# force_password_change.sh
# 功能说明:
# 1. 强制指定用户或所有用户在下次登录时更改密码。
# 2. 支持通过命令行直接指定用户名，或批量处理所有用户。
# 3. 适用于安全审计、密码更新或用户权限变更场景。

# 强制用户更改密码的函数
force_password_change_for_user() {
  local username="$1"

  if id "$username" &>/dev/null; then
    sudo chage -d 0 "$username" 2>/dev/null
    if [[ $? -eq 0 ]]; then
      echo "User $username is now required to change password on next login."
    else
      echo "Failed to enforce password change for user $username."
    fi
  else
    echo "User $username does not exist. Skipping..."
  fi
}

# 强制所有用户更改密码的函数
force_password_change_for_all_users() {
  echo "Forcing password change for all users..."
  local users=$(cut -d: -f1 /etc/passwd)

  for user in $users; do
    # 忽略系统用户
    local shell=$(getent passwd "$user" | cut -d: -f7)
    if [[ "$shell" != "/sbin/nologin" && "$shell" != "/usr/sbin/nologin" && "$shell" != "/bin/false" ]]; then
      force_password_change_for_user "$user"
    fi
  done
}

# 主函数
main() {
  if [[ $# -eq 0 ]]; then
    echo "Usage: $0 [username] | --all"
    echo "  username: Force password change for the specified user."
    echo "  --all: Force password change for all users."
    exit 1
  fi

  case "$1" in
    --all)
      force_password_change_for_all_users
      ;;
    *)
      force_password_change_for_user "$1"
      ;;
  esac
}

# 执行主函数
main "$@"

